<template>
  <div
    class="flex h-[200px] justify-between p-3 w-[60vw]"
    style="margin: 0 auto"
  >
    <div class="left flex">
      <n-image
        class="w-[260px] h-full"
        :src="buildPicUrl(examInfo?.pic || 'xxx')"
        fallback-src="../../../assets/images/R-C.png"
      ></n-image>
      <div class="text-[20px]">{{ examInfo?.name || '' }}</div>
    </div>

    <div class="right flex flex-col justify-between">
      <div class="price">价格：{{ examInfo?.price || '100' }}</div>
      <div class="option">
        <n-button type="success" @click="handleToPaperList" class="mr-2">
          开始做题
        </n-button>
        <n-button type="error" @click="handleToActive" v-if="!isActive">
          立即激活
        </n-button>
      </div>
    </div>
  </div>

  <n-modal
    :show="showModal"
    title="确认"
    preset="dialog"
    positive-text="确定"
    negative-text="取消"
    @positive-click="handleActive"
    @negative-click="showModal = false"
  >
    <n-form
      ref="formRef"
      :label-width="80"
      :model="formValue"
      :rules="rules"
      size="small"
    >
      <n-form-item label="激活码" path="code">
        <n-input v-model:value="formValue.code" placeholder="输入激活码" />
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import type { ExamRes } from '@/types/exam'
import { buildPicUrl } from '@/utils/commonBusiness'
import { getExamById } from '@/api/exam'
import {
  createUserActiveExam,
  getUserActiveExamByPage
} from '@/api/userActiveExam'
import type { FormInst } from 'naive-ui'
import { useMessage } from 'naive-ui'
import useUserStore from '@/stores/modules/user'

const examInfo = ref<ExamRes>()
const userStore = useUserStore()

const route = useRoute()
const router = useRouter()
const showModal = ref(false)
const formRef = ref<FormInst | null>(null)
const message = useMessage()

// 获取详情
const loadExamById = () => {
  getExamById(route.query.examId as string).then((res) => {
    examInfo.value = res.data.exam
  })
}

onMounted(() => {
  loadExamById()
  checkUserActive()
})

const rules = {
  code: {
    required: true,
    message: '请输入激活码',
    trigger: 'blur'
  }
}

const handleToPaperList = () => {
  router.push({
    name: 'chapterList',
    query: {
      examId: route.query.examId
    }
  })
}
const formValue = reactive({
  code: ''
})
const handleToActive = () => {
  // 需要验证用户是否登录
  if (!userStore.token) {
    router.push({
      name: 'login'
    })
    return
  }
  if (!userStore.userInfo) {
    userStore.getUserInfo().then(() => {
      showModal.value = true
    })
  } else {
    showModal.value = true
  }
}

const handleActive = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      // 激活
      createUserActiveExam({
        examId: route.query.examId as string,
        activeCode: formValue.code
      })
        .then(() => {
          message.success('激活成功')
          showModal.value = false
          checkUserActive()
        })
        .catch(() => {
          message.error('激活失败')
        })
    } else {
      console.log(errors)
      message.error('表单格式有误')
    }
  })
}

// 查询用户是否已经激活
const isActive = ref(false)
const checkUserActive = async () => {
  if (!userStore.token) {
    isActive.value = false
    return
  }

  if (!useUserStore().userInfo) {
    await userStore.getUserInfo()
  }

  const res = await getUserActiveExamByPage({
    page: 1,
    pageSize: 10,
    examId: route.query.examId as string,
    userId: useUserStore().userInfo?.id
  })

  if (res.data.items.length > 0) {
    isActive.value = true
    return
  }

  isActive.value = false
}
</script>

<style scoped lang="scss"></style>
